﻿using Common.Attributes;
using Domain.Entities;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
using MediatR;
using Application.Common.Interfaces;
using AutoMapper;

namespace Application.Features.Roles.Commands.Add;

/// <summary>
/// 创建角色
/// </summary>
[Map(typeof(Role))]
[Description("创建")]
[GroupDescription(("角色管理"))]
public class AddRoleCommand : IRequest<bool>
{
    /// <summary>
    /// 角色名称
    /// </summary>
    [Required(ErrorMessage = "角色名称必填")]
    public string RoleName { get; set; }

    /// <summary>
    /// 角色标识
    /// </summary>
    [Required(ErrorMessage = "角色标识必填")]
    public string RoleCode { get; set; }

    /// <summary>
    /// 角色描述
    /// </summary>
    [Required(ErrorMessage = "角色描述必填")]
    public string Description { get; set; }
}

/// <summary>
/// 处理程序
/// </summary>
public class AddRoleCommandHandler : IRequestHandler<AddRoleCommand, bool>
{
    private readonly IApplicationDbContext _context;
    private readonly IMapper _mapper;

    public AddRoleCommandHandler(
        IApplicationDbContext context,
        IMapper mapper)
    {
        _context = context;
        _mapper = mapper;
    }

    /// <summary>
    /// 业务逻辑
    /// </summary>
    /// <param name="request">请求参数</param>
    /// <param name="cancellationToken">取消标记</param>
    /// <returns>返回处理结果</returns>
    public async Task<bool> Handle(AddRoleCommand request, CancellationToken cancellationToken)
    {
        var role = _mapper.Map<Role>(request);
        await _context.Roles.AddAsync(role);

        return true;
    }
}